<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="餐桌号" prop="tableId">
        <el-input
          v-model="queryParams.tableId"
          placeholder="请输入餐桌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="infoList"
      row-key="orderId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'orderListVOList'}"
    >
      <el-table-column label="订单编号" align="center" prop="orderNumber"/>
      <el-table-column label="餐桌号" align="center" prop="tableId"/>
      <el-table-column label="用餐人数" align="center" prop="dinerNum"/>
      <el-table-column label="订单金额" align="center" prop="orderAmount"/>
      <el-table-column label="订单状态" align="center" prop="orderStatusName"/>
      <el-table-column label="下单用户" align="center" prop="userName"/>
      <el-table-column label="备注" align="center" prop="remark"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 判断是否有子节点 -->
          <template v-if="scope.row.parentId != 0">
            <!-- 子节点操作：编辑和删除 -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="getOrderDetail(scope.row.orderId)"
              v-hasPermi="['system:info:add']"
            >查看
            </el-button>
            <el-button
              v-if="scope.row.isLastItem"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row.orderId,scope.row.parentId)"
              v-hasPermi="['system:info:edit']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="delOrder(scope.row)"
              v-hasPermi="['system:info:remove']"
            >删除
            </el-button>

          </template>
          <template v-else>
            <!-- 主节点操作：查看、结算和删除 -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="getOrderDetail(scope.row.orderId)"
              v-hasPermi="['system:info:add']"
            >查看
            </el-button>
            <el-button v-if="scope.row.orderStatus==1 || (scope.row.orderStatus==0 && scope.row.orderListVOList.length==0) "
                       size="mini"
                       type="text"
                       icon="el-icon-edit"
                       @click="handleUpdate(scope.row.orderId,scope.row.parentId)"
                       v-hasPermi="['system:info:edit']"
            >编辑
            </el-button>
            <el-button v-if="scope.row.orderStatus==1"
                       v-loading="loading"
                       size="mini"
                       type="text"
                       icon="el-icon-check"
                       @click="settlementOrder(scope.row)"
                       v-hasPermi="['system:info:edit']"
            >结算
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:info:remove']"
            >删除
            </el-button>
          </template>
        </template>
      </el-table-column>

    </el-table>

    <!-- 查看商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" :before-close="handleClose" width="500px" append-to-body>
      <div>
        <div style="height: 50px;display: flex; align-items: center; justify-content: center">
          <div class="detailConact">商品图片</div>
          <div class="detailConact">商品名称</div>
          <div class="detailConact">商品数量</div>
          <div class="detailConact">商品价格</div>
        </div>
        <div v-for="(item,index) in orderDetailList"
             style="display: flex; justify-content: center; align-items: center;margin-bottom: 5px "
        >
          <el-image :src=$getPicture(item.shopPic) width="100%" style="flex: 1;height: 50px"></el-image>
          <div style="flex: 1; display: flex; flex-direction: column ">
            <div class="detailConact">{{ item.shopName }}</div>
            <div class="flavourStyle">{{ item.flavourName }}</div>
          </div>

          <div class="detailConact">{{ item.shopNum }}</div>
          <div class="detailConact">{{ item.shopAmount }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="display: flex;align-items: center;">
        <div style="flex: 1;display: flex; justify-content: left ">总价格：¥{{ amount }}</div>
        <div style="flex: 1">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 修改订单对话框 -->
    <el-dialog title="编辑订单" :visible.sync="show" :before-close="handleClose" width="500px" append-to-body>
      <div>
        <div style="height: 50px;display: flex; align-items: center; justify-content: center">
          <div class="detailConact">商品图片</div>
          <div class="detailConact">商品名称</div>
          <div class="detailConact">商品数量</div>
          <div class="detailConact">商品价格</div>
        </div>
        <div v-for="(item,index) in orderDetailList"
             style="display: flex; justify-content: center; align-items: center;margin-bottom: 5px "
        >
          <el-image :src=$getPicture(item.shopPic) width="100%" style="flex: 1;height: 50px"></el-image>
          <div style="flex: 1; display: flex; flex-direction: column ">
            <div class="detailConact">{{ item.shopName }}</div>
            <div class="flavourStyle">{{ item.flavourName }}</div>
          </div>
          <div class="detailConact">
            <el-input style="width: 40px" v-model="item.shopNum" placeholder="请输入商品数量"/>
          </div>
          <div class="detailConact">{{ item.shopAmount }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer" style="display: flex;align-items: center;">
        <div style="flex: 1" slot="footer" class="dialog-footer">
          <el-button v-if="change" type="primary" @click="conform">确 定</el-button>
          <el-button v-else v-loading="loading" type="primary" @click="associatedConform">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>


    <audio id="autoPlay" :src="music"></audio>
  </div>
</template>

<script>
import {
  listOrderinfo,
  getOrderDetail,
  delOrderinfo,
  delOrderAssociate,
  addOrderinfo,
  updateOrderinfo,
  updateOrderDetail,
  updateOrderAssociatedDetail,
  settlement
} from '@/api/orderEat/orderinfo'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import decimal from 'decimal.js'

export default {
  name: 'Info',
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 订单信息表格数据
      infoList: [],
      // 订单信息树选项
      infoOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示查看弹出层
      open: false,
      // 是否显示查看弹出层
      show: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        orderNumber: null,
        tableId: null,
        dinerNum: null,
        orderAmount: null,
        orderStatus: null,
        userId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //订单详情
      orderDetailList: [],
      //订单价格
      amount: 0,
      //已选择的订单ID
      orderId: 0,
      //主子订单修改切换
      change: true,
      // websocket数据
      websock: null,
      url: 'ws://localhost:8080/websocket/message',
      //url: 'ws://43.138.22.133:8080/websocket/message',
      msg: 'ss',
      sound: true,
      music: '',
      orderMusic: '/orderAlert.mp3',
      onlineMusic: '/online.wav',
      payMusic:'/voice.wav'
    }
  },
  created() {
    this.getList()
    this.playAudio()
    this.connect()
  },
  methods: {
    /** 打开webSocket连接 */
    connect() {
      const wsuri = this.url
      this.websock = new WebSocket(wsuri)
      this.websock.onopen = () => {
        console.log('WebSocket connected')
        this.playAudio(this.onlineMusic);
        //this.renewMessage()
        // 可以在这里发送一个消息表示加入
        // this.ws.send('joined');
      }
      this.websock.onmessage = (event) => {
        this.msg = event.data
        if (this.msg == 'add') {
          this.playAudio(this.orderMusic);
        }else if (this.msg == 'edit'){
          this.playAudio(this.payMusic);
        }
        else {
          console.log('订单结算')
        }
        this.getList()
      }
    },
    /** 服务端内容变更，更新websocket*/
    renewMessage() {
      this.websock.onmessage = (event) => {
        this.msg = event.data
        if (this.msg == 'add') {

        }
        this.playAudio()
        this.getList()
      }
    },
    /** 播放音频 */
    playAudio(parm) {
      const audio = document.getElementById('autoPlay')
      if (audio) {
        audio.pause()
        audio.currentTime = 0
        audio.src = parm
        audio.load()
        audio.play()
          .then(() => {
            console.log('播放音频了')
          })
          .catch(error => {
            console.error('Audio playback failed:', error)
          })
      }
    },

    /** 查询订单信息列表 */
    getList() {
      this.loading = true
      listOrderinfo(this.queryParams).then(response => {
        this.infoList = this.handleTree(response.data, 'orderId', 'parentId')
        // 遍历infoList并处理每个orderListVOList
        this.infoList.forEach(item => {
          if (item.orderListVOList && item.orderListVOList.length > 0) {
            item.orderListVOList.forEach((childItem, index, array) => {
              // 为orderListVOList中的每个元素添加isLastItem标志
              childItem.isLastItem = index === array.length - 1;
            });
          }
        });
        this.loading = false
      })
    },
    /** 转换订单信息数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.orderId,
        label: node.orderNumber,
        children: node.children
      }
    },
    /** 查询订单信息下拉树结构 */
    getTreeselect() {
      listInfo().then(response => {
        this.infoOptions = []
        const data = { orderId: 0, orderNumber: '顶级节点', children: [] }
        data.children = this.handleTree(response.data, 'orderId', 'parentId')
        this.infoOptions.push(data)
      })
    },
    /** 主订单确认修改 */
    conform() {
      let data = {
        shopCartList: this.orderDetailList,
        orderId: this.orderId
      }
      updateOrderDetail(data).then(response => {
        this.$modal.msgSuccess('修改成功')
        this.show = false
        this.getList()
      })
    },

    /** 追加订单确认修改 */
    associatedConform() {
      this.loading = true;
      let data = {
        shopCartList: this.orderDetailList,
        orderId: this.orderId
      }
      updateOrderAssociatedDetail(data).then(response => {
        this.$modal.msgSuccess('修改成功');
        this.show = false;
        this.getList();
        this.loading = false;
      }).catch(error => {
        // 处理可能的错误
        this.loading = false; // 确保在出错时也关闭加载提示
      });
    },
    /** 结算订单 */
    settlementOrder(data){
      this.loading = true
      this.$modal.confirm('是否确认结算').then(function() {
        return settlement(data)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('已结算')
        this.loading = false;
      }).catch(error => {
        this.loading = false; // 确保在出错时也关闭加载提示
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.show = false
      this.amount = 0
    },
    //关闭对话框
    handleClose() {
      this.open = false
      this.show = false
      this.amount = 0
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        parentId: null,
        orderNumber: null,
        tableId: null,
        dinerNum: null,
        orderAmount: null,
        orderStatus: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 查看订单详情*/
    getOrderDetail(row) {
      this.title = '订单详情'
      this.open = true
      getOrderDetail(row).then(response => {
        this.orderDetailList = response.data
        this.orderDetailList.forEach((order) => {
          this.amount = new decimal(this.amount).add(new decimal(order.shopAmount).mul(order.shopNum))
        })
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(orderId,parentId) {
      this.show = true
      if (parentId!=0){
        this.change = false
        this.orderId = orderId
        getOrderDetail(orderId).then(response => {
          this.orderDetailList = response.data
        })
      }else {
        this.orderId = orderId
        this.change = true
        getOrderDetail(orderId).then(response => {
          this.orderDetailList = response.data
          this.orderDetailList.forEach((order) => {
            this.amount = new decimal(this.amount).add(new decimal(order.shopAmount).mul(order.shopNum))
          })
        })
      }
    },
    /** 删除主订单操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除餐桌号为"' + row.tableId + '"的订单？').then(function() {
        return delOrderinfo(row.orderId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 删除追加订单操作 */
    delOrder(row){
      this.$modal.confirm('是否确认删除"' + row.orderNumber + '"').then(function() {
        return delOrderAssociate(row.orderId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }

  }
}
</script>
<style>
.detailConact {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center
}
.flavourStyle{
  color: grey;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center
}

</style>
